<template>
  <v-layout type="main">
    <!-- <p class="page-title">模型开发</p> -->
    <div class="detail-layout">
      <br />
      <el-form
        class="form myself-form alick-add-form"
        ref="form"
        :model="addForm"
        :rules="submitRules"
        x
        label-width="120px"
      >
        <div v-if="active == 1 || active == 9">
          <h3 class="add-alike-title">基本信息</h3>
          <el-form-item label="类型" prop="type">
            <el-radio v-model="addForm.is_webide" :label="true"
              >VsCode</el-radio
            >
            <el-radio v-model="addForm.is_webide" :label="false"
              >Jupyter</el-radio
            >
          </el-form-item>
          <el-form-item label="名称" prop="name">
            <el-input maxlength="40" v-model="addForm.name" />
          </el-form-item>
          <el-form-item label="描述" prop="desc">
            <el-input
              type="textarea"
              maxlength="200"
              :rows="3"
              v-model="addForm.desc"
            />
          </el-form-item>
          <el-form-item label="配图">
            <media-uploader
              accept=".jpg,.jpeg,.png,.JPG,.JPEG"
              :src="addForm.avatar"
              @avatarPath="avatarPath"
            />
          </el-form-item>
          <el-form-item label="" prop="tensorboard">
            <el-checkbox v-model="addForm.tensorboard">tensorboard</el-checkbox>
          </el-form-item>
          <h3 class="add-alike-title">仿真环境配置</h3>
          <el-form-item label="仿真环境" prop="simulation_node_group">
            <el-select
              v-model="simulation.image_id"
              @change="changeSimulationImage()"
              prop="simulation_image_id"
              class="full-extent-select"
            >
              <el-option
                v-for="item in simulationImageOptions"
                :value="item.id"
                :label="item.name"
                :key="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="想定" prop="scenario_id">
            <el-select
              value-key="id"
              v-model="scenario"
              @change="changeScenario(scenario)"
              prop="scenario_id"
              class="full-extent-select"
            >
              <el-option
                v-for="item in scenarioOptions"
                :value="item"
                :label="item.name"
                :key="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="推演方">
                        <div class="outin-box" v-for="(e, i) in simulation_deduction_list" :key="i">
                            <div class="outin-input">
                                <div class="outin-input-name">
                                    <el-form-item :label="e.name">
                                        <el-select  v-model="e.type">
                                            <el-option :value='1' label="我方" />
                                            <el-option :value='2' label="对手" />
                                        </el-select>
                                    </el-form-item>
                                    <el-form-item v-if="e.type != 1" label="模型" prop="model_id">
                                        <el-select v-model="e.model_id" @change="changeModel(e.model_id, i)"
                                            style="width:100%;" :popper-append-to-body="false"
                                            popper-class="select-popper" placeholder="请选择">
                                            <el-option v-for="item in modelOptions" :key="item.id" :label="item.name"
                                                :value="item.id">
                                            </el-option>
                                        </el-select>
                                    </el-form-item>
                                    <el-form-item v-if="e.type != 1" label="版本" prop="model_version_id">
                                        <el-select v-model="e.model_version_id" @change=changeModelVersion()
                                            style="width:100%;" :popper-append-to-body="false"
                                            popper-class="select-popper" placeholder="请选择">
                                            <el-option v-for="item in e.modelVersionOptions" :key="item.id"
                                                :label="item.version" :value="item.id">
                                            </el-option>
                                        </el-select>
                                    </el-form-item>
                                </div>
                            </div>
                        </div>
                    </el-form-item> -->
          <el-form-item label="数量">
            <el-input-number v-model="simulation.pod_num"></el-input-number>
          </el-form-item>
          <!-- <el-form-item label="启动命令行" prop="command">
                        <el-input type="textarea" @input="onInput" :rows="2" v-model="simulation.command" />
                    </el-form-item> -->
          <!-- <el-form-item label="端口" prop="port">
                        <div class="outin-box" v-for="(e, i) in simulation_port_list" :key="i">
                            <div class="port-lis">
                                <el-radio-group v-model="e.protocol" class="port-lis-radio">
                                    <el-radio :label="2">tcp</el-radio>
                                    <el-radio :label="1">http</el-radio>
                                </el-radio-group>
                                <el-input type="text" v-model="e.port"  class="port-el-input" />
                            </div>
                        </div>
                    </el-form-item> -->
          <h3 class="add-alike-title">算法</h3>
          <el-form-item label="算法名称" prop="algorithm_name">
            <el-select
              v-model="addForm.algorithm_name"
              style="width: 100%"
              :popper-append-to-body="false"
              filterable
              allow-create
              popper-class="select-popper"
              placeholder="请选择"
            >
              <el-option
                v-for="item in algorithms"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="状态空间">
            <el-input-number v-model="addForm.n_state"></el-input-number>
          </el-form-item>
          <el-form-item label="动作空间">
            <el-input-number v-model="addForm.n_action"></el-input-number>
          </el-form-item>

          <h3 class="add-alike-title">开发环境配置</h3>
          <div class="node-module">
            <h3 class="node-module-title">主节点</h3>
            <el-form-item label="环境" prop="mainNodeImageId">
              <el-cascader
                v-model="mainNode.image_group"
                :options="imageOptions"
                :show-all-levels="false"
                class="full-extent-select"
              ></el-cascader>
            </el-form-item>
            <el-form-item label="资源组" prop="mainProduct">
              <el-select
                v-model="mainNode.product_id"
                prop="main_product"
                class="full-extent-select"
              >
                <el-option
                  v-for="item in productOptions"
                  :value="item.id"
                  :label="item.name"
                  :key="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <div class="right-btn-box" v-if="slaveNodeList.length == 0">
              <span class="outin-handle">
                <a href="javascript:;" @click="addSlaveNode()">增加</a>
              </span>
            </div>
          </div>
          <div v-for="(tag, i) in slaveNodeList" :key="i">
            <div class="node-module">
              <h3 class="node-module-title">从节点</h3>

              <el-form-item label="环境" prop="slaveImage">
                <el-cascader
                  v-model="tag.image_group"
                  :options="imageOptions"
                  :show-all-levels="false"
                  class="full-extent-select"
                ></el-cascader>
              </el-form-item>
              <el-form-item label="资源组">
                <el-select v-model="tag.product_id" class="full-extent-select">
                  <el-option
                    v-for="item in productOptions"
                    :value="item.id"
                    :label="item.name"
                    :key="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="数量">
                <el-input-number v-model="tag.pod_num"></el-input-number>
              </el-form-item>
              <div class="right-btn-box">
                <span class="outin-handle">
                  <a href="javascript:;" @click="delSlaveNode(i)">删除</a>
                  <a
                    href="javascript:;"
                    @click="addSlaveNode()"
                    v-if="i == slaveNodeList.length - 1"
                    >增加</a
                  >
                </span>
              </div>
            </div>
          </div>
          <div v-if="advanced == true">
            <h3 class="add-alike-title">输出配置</h3>
            <el-form-item label="端口映射">
              <plug-port
                :port_list="port_list"
                @infoPort="infoPort"
                v-if="port_list"
              />
            </el-form-item>
          </div>
          <div class="right-btn-box">
            <span class="outin-handle">
              <a href="javascript:;" @click="setAdvanced()">高级设置</a>
            </span>
          </div>
        </div>
        <div v-show="active == 2">
          <h1 class="succeed-hint">创建成功</h1>
          <div class="succeed-btn">
            <a href="javascript:;" class="start" @click="startTask">启动</a>
            <a href="javascript:;" class="go" @click="toDetail">立即前往</a>
          </div>
        </div>
        <el-form-item label=" ">
          <el-button
            v-if="active == 1"
            class="none-type"
            type="primary"
            @click="submmit"
            >确定</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </v-layout>
</template>

<script>
import { addGameExperiment, startGameExperiment } from "@/api/gameExperiment";
import { getMarketAlgorithmVersionDetail } from "@/api/marketAlgorithmVersion";
import { getAllImages, getImageDetail, getAllImageGroups } from "@/api/image";
import { mainImageRule, mainProductRule, slaveImageRule } from "@/utils/rule";
import { getAllProducts } from "@/api/product";
import { getAllScenarios } from "@/api/scenario";
import { algorithms } from "@/utils/maps";
// import plugDataset from "@/components/module/plug-in-dataset";
// import plugS3 from "@/components/module/plug-in-s3";
// import plugModel from "@/components/module/plug-in-model";
import plugPort from "@/components/module/plug-in-port";
import { paramMap } from "@/utils/maps";
export default {
  data() {
    return {
      s3_flag: paramMap["s3_flag"],
      active: 1,
      advanced: false,
      addForm: {
        name: "",
        desc: "",
        is_webide: true,
        n_state: 100,
        n_action: 10,
      },
      algorithms,
      submitRules: {
        name: [
          { required: true, message: "该项为必填项" },
          { required: true, min: 1, max: 40, message: "长度在1到40个字符" },
        ],
        desc: [
          { required: true, message: "该项为必填项" },
          { required: true, min: 1, max: 200, message: "长度在1到200个字符" },
        ],
        // scenario_id: [
        //     { required: true, message: "该项为必填项" },
        // ],
        // simulation_node_group: [
        //     { required: true, message: "该项为必填项" },
        // ],
        main_image_id: [{ required: true, message: "该项为必填项" }],
        main_product: [{ required: true, message: "该项为必填项" }],
        mainNodeImageId: [
          {
            required: true,
            validator: mainImageRule.bind(this, this),
            trigger: "change",
          },
        ],
        mainProduct: [
          {
            required: true,
            validator: mainProductRule.bind(this, this),
            trigger: "change",
          },
        ],
        tagImageId: [
          {
            required: true,
            validator: slaveImageRule.bind(this, this),
            trigger: "change",
          },
        ],
        // port: [
        //   { required: true, message: "请填写端口" },
        // ]
      },
      simulation: { pod_num: 1 },
      mainNode: {
        visibility: "2",
        engine: "2",
        pod_num: 1,
        type: 0,
        imageOptions: [],
        image_id: null,
      },
      slaveNodeList: [],
      simulation_port_list: [],
      imageOptions: [],
      productOptions: [],
      scenarioOptions: [],
      simulationImageOptions: [],
      modelOptions: [],
      modelVersionOptions: [],
      dataset_list: [],
      in_s3_list: [],
      model_list: [],
      out_s3_list: [],
      port_list: [],
      scenario: null,
      path: "",
      bizId: "",
      algorithmVersion_id: this.$route.query.algorithmVersion_id,
      algorithm_name: this.$route.query.algorithm_name,
      algorithm_desc: this.$route.query.algorithm_desc,
      algorithm_avatar: this.$route.query.algorithm_avatar,
      podUrl: [],
    };
  },
  components: {
    // plugDataset,
    // plugS3,
    // plugModel,
    plugPort,
  },
  async created() {
    this.getData();
    this.getAllImageGroups();
    this.getProductList();
    this.getSimulationImage();
    //this.getModelList()
  },
  async mounted() {
    this.$forceUpdate();
  },
  methods: {
    setAdvanced() {
      this.advanced = !this.advanced;
    },
    async setAddForm() {
      console.log('开始');
      this.addForm.node_group_list = [];
      this.mainNode.type = 1;
      this.mainNode.image_id = this.mainNode.image_group[2];
      this.addForm.node_group_list.push(this.mainNode);
      for (let i = 0; i < this.slaveNodeList.length; i++) {
        this.slaveNodeList[i].type = 2;
        this.slaveNodeList[i].image_id = this.slaveNodeList[i].image_group[2];
        this.addForm.node_group_list.push(this.slaveNodeList[i]);
      }
      console.log("print port_list", this.port_list.length)
      this.addForm.port_list = []
      for (let i = 0; i < this.port_list.length; i++) {
        this.addForm.port_list.push(this.port_list[i])
      }
      console.log(this.addForm.port_list);
      console.log(this.addForm.node_group_list);
      this.addForm.simulation_port_list = [];
      this.addForm.simulation_deduction_list = [];
      if (this.simulation.image_id) {
        this.addForm.simulation_port_list = this.simulation_port_list;
        this.addForm.simulation_deduction_list = [];
        this.addForm.simulation_node_group = this.simulation;
        this.addForm.simulation_node_group.image_id = this.simulation.image_id;
        this.addForm.scenario_id = this.scenario.id;
      }
      console.log("addForm", this.addForm);
    },
    avatarPath(data) {
      this.addForm.avatar = data;
    },
    onInput() {
      this.$forceUpdate();
    },
    async getAddForm(data) {
      this.addForm = { ...this.addForm, ...data };
      this.port_list = [];
      this.slaveNodeList = [];
      for (let node of data.node_group_list) {
        if (node.type == 1) {
          this.mainNode = node;
          let res = await getImageDetail({ id: this.mainNode.image_id });
          let mainImage = res.data;
          this.mainNode.image_group = [
            mainImage.visibility.toString(),
            mainImage.engine.toString(),
            mainImage.id,
          ];
        } else {
          let res = await getImageDetail({ id: node.image_id });
          let slaveImage = res.data;
          let slaveNode = node;
          slaveNode.image_group = [
            slaveImage.visibility.toString(),
            slaveImage.engine.toString(),
            slaveImage.id,
          ];
          this.slaveNodeList.push(slaveNode);
        }
      }
      this.simulation = this.addForm.simulation_node_group;
      if (!this.simulation) {
        this.simulation = { pod_num: 1 };
      }
      this.scenario = this.addForm.scenario;
      this.changeSimulationImage();
      this.changeScenario(this.scenario);
      this.simulation_port_list = data.simulation_port_list;
    },
    async getData() {
      if (this.algorithmVersion_id) {
        let res = await getMarketAlgorithmVersionDetail({
          id: this.algorithmVersion_id,
        });
        res.data.algorithm_version_id = this.algorithmVersion_id;
        this.getAddForm(res.data);
        this.addForm.name = this.algorithm_name;
        this.addForm.desc = this.algorithm_desc;
        this.addForm.avatar = this.algorithm_avatar;
      }
    },
    async submmit() {
      console.log('submmit addForm',this.addForm);
      this.setAddForm();
      console.log('submmit addForm',this.addForm);
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          this.addForm.id = null;
          let res = await addGameExperiment({ ...this.addForm, pre_code: 6 });
          this.getAddForm(res.data);
          console.log('jieshu');
          this.bizId = res.data.id;
          if (res && res.data) {
            this.active = 2;
          }
        }
      });
    },
    async changeSimulationImage() {
      if (this.simulation) {
        let ret = await getAllScenarios({ imageId: this.simulation.image_id });
        console.log("ret", ret.data);
        this.scenarioOptions = ret.data;
        let simulationCommand = this.simulation.command;
        if (this.simulation.image_id) {
          let res = await getImageDetail({ id: this.simulation.image_id });
          let image = res.data;
          this.simulation_port_list = image.port_list;
          this.simulation.product_id = image.product_id;
          this.simulation.command = image.command;
        }
        if (simulationCommand != null) {
          this.simulation.command = simulationCommand;
        }
      }
    },
    async changeScenario(scenario) {
      if (scenario) {
        console.log(scenario);
        this.scenario = scenario;
        // 如果是新建任务通过调用想定命令接口更新仿真命令
        //this.getModelList()
        if (this.$route.query.id) {
          return;
        }
      }
    },

    async startTask() {
      await startGameExperiment({ id: this.bizId });
      this.toDetail();
    },
    toDetail() {
      console.log("addForm", this.addForm);
      let query = {
        id: this.addForm.id,
      };
      this.$router.push({
        path: "/algorithmAnalysis/code",
        query,
      });
    },
    async getAllImageGroups() {
      let res = await getAllImageGroups();
      this.imageOptions = res.data;
    },
    async getProductList() {
      let res = await getAllProducts();
      this.productOptions = res.data;
    },
    async getSimulationImage() {
      let ret = await getAllImages({ visibility: "1", type: 3 });
      this.simulationImageOptions = ret.data;
    },
    succeedOver(data) {
      console.log(data);
    },
    // async changeMasterEngine(visibility, engine) {

    //     let ret = await getAllImages({ visibility: visibility, engine: engine, type: 1 })
    //     this.mainNode.imageOptions = ret.data
    //     this.mainNode = JSON.parse(JSON.stringify(this.mainNode))
    //     console.log('mainNode', this.mainNode)
    // },
    // async changeSlaveEngine(visibility, engine, i) {
    //     let ret = await getAllImages({ visibility: visibility, engine: engine, type: 1 })
    //     this.slaveNodeList[i].imageOptions = ret.data
    //     this.slaveNodeList = JSON.parse(JSON.stringify(this.slaveNodeList))
    // },
    addSlaveNode() {
      this.slaveNodeList.push({
        visibility: "2",
        engine: "2",
        type: 1,
        imageOptions: [],
        pod_num: 1,
      });
    },
    delSlaveNode(i) {
      this.slaveNodeList.splice(i, 1);
    },
    infoInS3(s3s) {
      this.in_s3_list = s3s;
    },
    infoOutS3(s3s) {
      this.out_s3_list = s3s;
    },
    infoModel(models) {
      this.model_list = [];
      console.log("modes", models);
      // models.forEach(e => { e.model_version_id = e.version.id
      //   e.model_id = e.id })
      this.model_list = models;
    },
    infoPort(ports) {
      this.port_list = ports;
      console.log(this.port_list);
    },
    infoDataset(datasets) {
      this.dataset_list = [];
      datasets.forEach((e) => {
        e.dataset_id = e.id;
        e.dataset = {
          name: e.name,
          alias: e.alias,
          id: e.id,
        };
      });
      this.dataset_list = datasets;
      console.log("infoDataset", datasets);
    },
  },
};
</script>
<style lang="less" scoped>
@import "~@/assets/css/detail-add.less";
</style>
